package com.nowcoder.community.controller.interceptor;

import com.nowcoder.community.entity.LoginTicket;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.service.UserService;
import com.nowcoder.community.util.CookieUtil;
import com.nowcoder.community.util.HostHolder;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.web.context.SecurityContextRepository;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.Date;

@Component
public class LoginTicketInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private SecurityContextRepository securityContextRepository;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从cookie获取凭证ticket
        String ticket = CookieUtil.getValue(request, "ticket");
        if(ticket != null) {
            // 从login_ticket表中查询凭证
            LoginTicket loginTicket = userService.findLoginTicket(ticket);
            // 判断凭证是否有效
            if(loginTicket != null) {
                if(loginTicket.getStatus() == 0 && loginTicket.getExpired().after(new Date())) {
                    // 根据凭证查询用户
                    User user = userService.findUserById(loginTicket.getUserId());
                    // 在本次请求的处理过程中持有用户信息
                    // 请求处理完毕后，随着线程的消除而消除
                    hostHolder.setUsers(user);

                    // 构建用户认证结果
                    // 并存入Spring Security的Context
                    // 以便于Spring Security进行授权
                    Authentication authentication = new UsernamePasswordAuthenticationToken(
                            user,
                            user.getPassword(),
                            userService.getAuthorities(user.getId())
                    );
                    SecurityContextHolder.setContext(new SecurityContextImpl(authentication));
                    securityContextRepository.saveContext(SecurityContextHolder.getContext(), request, response);
                }
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        User user = hostHolder.getUsers();
        if(user != null && modelAndView != null) {
            modelAndView.addObject("loginUser", user);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 避免ThreadLocal引起的堆空间溢出
        hostHolder.clear();
        // 清楚Spring Security的Context
        // SecurityContextHolder.clearContext();
    }
}
